package fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.yztc.thinkpad.mandemo.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import contans.HomeBb;
import contans.HomeDp;
import contans.HomeVpUrl;
import homeactivity.PingPaiOneActivity;
import homeadapter.GrideBangBangViewAdapter;
import homeadapter.GrideSpecViewAdapter;
import homeadapter.GrideViewAdapter;
import homeadapter.HomeListViewAdapter;
import homebean.BangBangBean;
import homebean.HomevpBean;
import homebean.PingpaiBean;
import homewebview.VpWebView;
import utils.BannerLayout;
import utils.MyGridView;
import utils.MyListView;
import utils.Okhttputils;


/**
 * //首页的Fragment
 * Created by Administrator on 2016/9/29.
 */
public class FragmentHome extends Fragment {

    @Bind(R.id.single_shop)
    ImageView singleShop;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.home_vp)
    BannerLayout homeVp;
    @Bind(R.id.home_gv)
    GridView homeGv;
    @Bind(R.id.iv_ppone)
    ImageView ivPpone;
    @Bind(R.id.iv_pptwo)
    ImageView ivPptwo;
    @Bind(R.id.iv_ppthree)
    ImageView ivPpthree;
    @Bind(R.id.iv_ppfour)
    ImageView ivPpfour;
    @Bind(R.id.iv_ppfive)
    ImageView ivPpfive;
    @Bind(R.id.iv_ppsix)
    ImageView ivPpsix;
    @Bind(R.id.iv_ppseven)
    ImageView ivPpseven;
    @Bind(R.id.ta_tv)
    TextView taTv;
    @Bind(R.id.fragment_home_layout)
    LinearLayout fragmentHomeLayout;
    @Bind(R.id.home_list_ivone)
    ImageView homeListIvone;
    @Bind(R.id.home_list_ivtwo)
    ImageView homeListIvtwo;
    @Bind(R.id.home_list_ivthree)
    ImageView homeListIvthree;
    @Bind(R.id.tv_home_lv)
    TextView tvHomeLv;
    @Bind(R.id.home_list_ivfour)
    ImageView homeListIvfour;
    @Bind(R.id.home_list_ivfive)
    ImageView homeListIvfive;
    @Bind(R.id.home_list_ivsix)
    ImageView homeListIvsix;
    @Bind(R.id.tv_home_lvtwo)
    TextView tvHomeLvtwo;
    @Bind(R.id.xue_tv)
    TextView xueTv;
    @Bind(R.id.home_list_view)
    MyListView homeListView;
    @Bind(R.id.home_te_gv)
    MyGridView homeTeGv;
    @Bind(R.id.home_bang_gv)
    MyGridView homeBangGv;
    private ProgressDialog pd;
    private  int  pagedex=1;
    private  PullToRefreshScrollView mScrollView;
    private View mView;
    private BannerLayout mhome_vp;
    private GrideViewAdapter mGvadapter;//
    private List<String> mList = new ArrayList<>();
    private List<HomevpBean.DataBean> mListBean = new ArrayList<>();//加载viewpage和cardView数据
    private List<PingpaiBean.DataBean.BrandBean> mListBrand = new ArrayList<>();//加载品牌精选
    private HomeListViewAdapter mListAdapter;
    private GrideSpecViewAdapter grideSpecViewAdapter;
    private GrideBangBangViewAdapter bangbangAdapter;
    private List<PingpaiBean.DataBean.MatchThemesBean> matchesBeanList = new ArrayList<>();//搭配精选
    private List<PingpaiBean.DataBean.SchoolBean> schoolBeanlist = new ArrayList<>();//特色市场
    private List<BangBangBean.DataBean.ItemDetailBean> bangbangBeanList = new ArrayList<>();//邦邦精选
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //viewpage轮播图
                    mListBean = (List<HomevpBean.DataBean>) msg.obj;
                    for (int i = 0; i < 6; i++) {
                        mList.add(mListBean.get(i).getTheme_image());
                    }
                    mhome_vp.setViewUrls(mList);
                    //viewpage的点击事件
                    mhome_vp.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            String url = mListBean.get(position).getTheme_link();
                            String theme_name=mListBean.get(position).getTheme_name();
                            Intent intent=new Intent(getActivity(), VpWebView.class);
                            intent.putExtra("url",url);
                            intent.putExtra("theme_name",theme_name);
                            startActivity(intent);
                        }
                    });
//                    //四个小图片和文字
                    mGvadapter = new GrideViewAdapter(getActivity(), mListBean);
                    homeGv.setAdapter(mGvadapter);
                    //特色专区
                    grideSpecViewAdapter = new GrideSpecViewAdapter(getActivity(), mListBean);
                    homeTeGv.setAdapter(grideSpecViewAdapter);
                    break;
                case 2:  //加载品牌
                    mListBrand = (List<PingpaiBean.DataBean.BrandBean>) msg.obj;
                    Glide.with(getActivity()).load(mListBrand.get(0).getBrandIcon()).into(ivPpone);
                    ivPpone.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(getActivity(), PingPaiOneActivity.class);
                            int BrandID=mListBrand.get(0).getBrandId();
                            String titleName=mListBrand.get(0).getBrandName();
                            intent.putExtra("BrandID",""+BrandID);
                            intent.putExtra("titleName",titleName);
                            startActivity(intent);
                        }
                    });
                    Glide.with(getActivity()).load(mListBrand.get(1).getBrandIcon()).into(ivPptwo);
                    ivPptwo.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(getActivity(), PingPaiOneActivity.class);
                            int BrandID=mListBrand.get(1).getBrandId();
                            String titleName=mListBrand.get(1).getBrandName();
                            intent.putExtra("BrandID",""+BrandID);
                            intent.putExtra("titleName",titleName);
                            startActivity(intent);
                        }
                    });
                    Glide.with(getActivity()).load(mListBrand.get(2).getBrandIcon()).into(ivPpthree);
                    ivPpthree.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(getActivity(), PingPaiOneActivity.class);
                            int BrandID=mListBrand.get(2).getBrandId();
                            String titleName=mListBrand.get(2).getBrandName();
                            intent.putExtra("BrandID",""+BrandID);
                            intent.putExtra("titleName",titleName);
                            startActivity(intent);
                        }
                    });
                    Glide.with(getActivity()).load(mListBrand.get(3).getBrandIcon()).into(ivPpfour);
                    ivPpfour.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(getActivity(), PingPaiOneActivity.class);
                            int BrandID=mListBrand.get(3).getBrandId();
                            String titleName=mListBrand.get(3).getBrandName();
                            intent.putExtra("BrandID",""+BrandID);
                            intent.putExtra("titleName",titleName);
                            startActivity(intent);
                        }
                    });
                    Glide.with(getActivity()).load(mListBrand.get(4).getBrandIcon()).into(ivPpfive);
                    ivPpfive.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(getActivity(), PingPaiOneActivity.class);
                            int BrandID=mListBrand.get(4).getBrandId();
                            String titleName=mListBrand.get(4).getBrandName();
                            intent.putExtra("BrandID",""+BrandID);
                            intent.putExtra("titleName",titleName);
                            startActivity(intent);
                        }
                    });
                    Glide.with(getActivity()).load(mListBrand.get(5).getBrandIcon()).into(ivPpsix);
                    ivPpsix.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent=new Intent(getActivity(), PingPaiOneActivity.class);
                            int BrandID=mListBrand.get(5).getBrandId();
                            String titleName=mListBrand.get(5).getBrandName();
                            intent.putExtra("BrandID",""+BrandID);
                            intent.putExtra("titleName",titleName);
                            startActivity(intent);
                        }
                    });
                    break;
                case 3://加载搭配
                    matchesBeanList = (List<PingpaiBean.DataBean.MatchThemesBean>) msg.obj;
                    tvHomeLv.setText(matchesBeanList.get(0).getThemeDesc());
                    Glide.with(getActivity()).load(matchesBeanList.get(0).getMatches().get(0).getBig_image()).placeholder(R.mipmap.default_banner).into(homeListIvone);
                    Glide.with(getActivity()).load(matchesBeanList.get(0).getMatches().get(1).getBig_image()).placeholder(R.mipmap.default_banner).into(homeListIvtwo);
                    Glide.with(getActivity()).load(matchesBeanList.get(0).getMatches().get(2).getBig_image()).placeholder(R.mipmap.default_banner).into(homeListIvthree);
                    tvHomeLvtwo.setText(matchesBeanList.get(1).getThemeDesc());
                    Glide.with(getActivity()).load(matchesBeanList.get(1).getMatches().get(0).getBig_image()).placeholder(R.mipmap.default_banner).into(homeListIvfour);
                    Glide.with(getActivity()).load(matchesBeanList.get(1).getMatches().get(1).getBig_image()).placeholder(R.mipmap.default_banner).into(homeListIvfive);
                    Glide.with(getActivity()).load(matchesBeanList.get(1).getMatches().get(2).getBig_image()).placeholder(R.mipmap.default_banner).into(homeListIvsix);
                    break;
                case 4://学堂精选
                    schoolBeanlist = (List<PingpaiBean.DataBean.SchoolBean>) msg.obj;
                    mListAdapter = new HomeListViewAdapter(getActivity(), schoolBeanlist);
                    homeListView.setAdapter(mListAdapter);
                    break;
                case 5://邦邦精选
                    if (pagedex==1){
                        bangbangBeanList = (List<BangBangBean.DataBean.ItemDetailBean>) msg.obj;
                        bangbangAdapter = new GrideBangBangViewAdapter(getActivity(), bangbangBeanList);
                        homeBangGv.setAdapter(bangbangAdapter);
                        mScrollView.onRefreshComplete();
                    }else
                    {
                        bangbangBeanList.addAll((List<BangBangBean.DataBean.ItemDetailBean>) msg.obj);
                        bangbangAdapter.notifyDataSetChanged();
                        mScrollView.onRefreshComplete();
//                        pd.dismiss();
                    }
                    break;
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home, null);
        initData();//初始化控件
        initViewVp();//加载viewpage和cardView数据
        initViewPp();//加载品牌精选
        initViewDp();//加载搭配精选
        initViewXt();//加载学堂
        initBangB();//加载邦邦精选
        fresh();//下拉刷新加载数据
        ButterKnife.bind(this, mView);
        return mView;
    }
    private void fresh() {
        mScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                pagedex=1;
                initBangB();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    pagedex++;
                    initBangB();
                }
        });
    }
    private void initBangB() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(HomeBb.BANGURL+pagedex+HomeBb.PAINDEX);
                    JSONObject obj = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String itemDetail = obj.getString("itemDetail");
                    List<BangBangBean.DataBean.ItemDetailBean> bangListBean = new ArrayList<>();
                    bangListBean = JSONArray.parseArray(itemDetail, BangBangBean.DataBean.ItemDetailBean.class);
                    Message message = new Message();
                    message.what = 5;
                    message.obj = bangListBean;
                    mHandler.sendMessage(message);
                    pd.dismiss();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void initViewXt() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(HomeDp.HOMEDP);
                    JSONObject obj = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String school = obj.getString("school");
                    List<PingpaiBean.DataBean.SchoolBean> sch = new ArrayList<PingpaiBean.DataBean.SchoolBean>();
                    sch = JSONArray.parseArray(school, PingpaiBean.DataBean.SchoolBean.class);
                    Message message = new Message();
                    message.what = 4;
                    message.obj = sch;
                    mHandler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initViewDp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(HomeDp.HOMEDP);
                    JSONObject obj = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String matchThemes = obj.getString("matchThemes");
                    List<PingpaiBean.DataBean.MatchThemesBean> match = new ArrayList<PingpaiBean.DataBean.MatchThemesBean>();
                    match = JSONArray.parseArray(matchThemes, PingpaiBean.DataBean.MatchThemesBean.class);
//                    Log.i("TAG", "------>" + match.size());
                    Message message = new Message();
                    message.what = 3;
                    message.obj = match;
                    mHandler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void initViewPp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //外面对象 里面data还是对象  对象里面是数组
                    String jsonString = Okhttputils.getInstance().run(HomeDp.HOMEDP);
//                    Log.i("TAG","json------>"+jsonString);
                    JSONObject object = JSONObject.parseObject(jsonString).getJSONObject("data");
                    String brand = object.getString("brand");
                    List<PingpaiBean.DataBean.BrandBean> mBrand = new ArrayList<PingpaiBean.DataBean.BrandBean>();
                    mBrand = JSONArray.parseArray(brand, PingpaiBean.DataBean.BrandBean.class);
//                    Log.i("TAG", "------>" + mschool.size());
                    Message message = new Message();
                    message.what = 2;
                    message.obj = mBrand;
                    mHandler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initViewVp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = Okhttputils.getInstance().run(HomeVpUrl.HOMEVPURL);
//                    Log.i("TAG","json------>"+jsonString);
                    String data = JSONObject.parseObject(jsonString).getString("data");
                    List<HomevpBean.DataBean> datas = new ArrayList<HomevpBean.DataBean>();
                    datas = JSONArray.parseArray(data, HomevpBean.DataBean.class);
//                    Log.i("TAG","datas------>"+datas.size());
                    Message message = new Message();
                    message.what = 1;
                    message.obj = datas;
                    mHandler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void initData() {
        mhome_vp = (BannerLayout) mView.findViewById(R.id.home_vp);
        mhome_vp.requestFocus();
        mhome_vp.setFocusable(true);
        mhome_vp.setFocusableInTouchMode(true);
        pd=ProgressDialog.show(getActivity(),"","小二正在努力加载");
        pd.setCancelable(true);
        mScrollView= (PullToRefreshScrollView) mView.findViewById(R.id.refresh);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
